import axios from 'axios';
import { MessageBox, Message } from 'element-ui';
import qs from 'qs';
import router from '../router/index';
import store from '@/store';
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BACK_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    var token = 'Bearer f5ef3274-3e1b-4f67-a24a-2fd31966e34c';
    // if (token == "" && localStorage.getItem("superToken") != '407404EAEC845F1B91A104B80FE86D89') {
    //   Message({
    //     message: "没有登陆信息，请从OA登录入口处九宫格页面中，点击进入职神籍",
    //     type: "error",
    //     duration: 5 * 1000,
    //   });
    // }
    if (config.data) {
      config.headers['id'] =
        config.data.ylPositionId ||
        config.data.positionId ||
        config.data.id ||
        0;
    } else if (config.params) {
      config.headers['id'] =
        config.params.ylPositionId ||
        config.params.positionId ||
        config.params.id ||
        0;
    } else {
      config.headers['id'] = 0;
    }

    //本地调试可打开注释
    // config.headers["platform"] = 0;
    config.headers["Authorization"] =
      "Bearer c1e4ad29-fb2e-4c88-99b3-be55933ce4f3";

    if (process.env.VUE_APP_BACK_API == '//192.168.0.218:8188/') {
      config.headers['n-d-version'] =
        // '{"yl1001-boot-career-report":"1.4","yl1001-boot-occupation-platform":"1.4","yl1001-boot-subject-database":"1.4","yl1001-boot-file":"1.4"}'; // 曾辉
        // '{"yl1001-boot-career-report":"3.0","yl1001-boot-occupation-platform":"3.0","yl1001-boot-subject-database":"3.0","yl1001-boot-file":"3.0"}'; // 龚祥
        '{"yl1001-boot-career-report":"1.9","yl1001-boot-occupation-platform":"1.9","yl1001-boot-subject-database":"1.9","yl1001-boot-file":"1.9"}'; // 高枫
    }
    //pc端专属秘钥
    // config.headers["SecretKey"] = "6c95e857588f5e3381d68e7bdfb9ad9b";
    var token = '';
    var SecretKey = '';
    if (localStorage.getItem('token')) {
      token = localStorage.getItem('token');
    } else if (localStorage.getItem('userInfo')) {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      token = userInfo.token;
    }
    if (localStorage.getItem('SecretKey')) {
      SecretKey = localStorage.getItem('SecretKey');
    }

    config.headers['Authorization'] = token;
    config.headers['SecretKey'] = SecretKey;
    return config;
  },
  (error) => {
    //console.log("config报错", error);
    // do something with request error
    return Promise.reject(error);
  }
);
function getTokenLogin() {
  let flashTime = localStorage.getItem('superTokenFlash') || 0;
  let currentTime = Math.floor(Date.now());
  let overFiveSeconds = currentTime - flashTime > 6000;
  if (overFiveSeconds) {
    let superToken = localStorage.getItem('superToken');
    let params = {};
    if (superToken == '407404EAEC845F1B91A104B80FE86D89') {
      params = {
        username: 'test1',
        password: '123456',
        grant_type: 'password',
        accountType: 'appAdmin',
        code: '0303b156fd538ea34e74be615eb62aec',
        captchaId: '0303b156fd538ea34e74be615eb62aec',
        client_id: '4bd805879fba42e088f13c191e574666',
        client_secret: 'b5007a8de70647d3bc31b90807b6145a'
      };
    } else {
      params = {
        username: 'testadmin',
        password: 'job1001.com',
        grant_type: 'password',
        accountType: 'appAdmin',
        code: '0303b156fd538ea34e74be615eb62aec',
        captchaId: '0303b156fd538ea34e74be615eb62aec',
        client_id: '4bd805879fba42e088f13c191e574666',
        client_secret: 'b5007a8de70647d3bc31b90807b6145a'
      };
    }
    axios({
      method: 'post',
      url: process.env.VUE_APP_BACK_API_TOKEN + 'api-auth/oauth/token',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: qs.stringify(params)
    }).then((res) => {
      if (res.data.code == 200 && res.data.data.token) {
        //console.log("/oauth/token res.data", res.data.data);

        let userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};
        userInfo.token = `${res.data.data.tokenHead}${res.data.data.token}`;
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        localStorage.setItem('superTokenFlash', currentTime);
        //重新请求错误的接口
        location.reload(true);
        // return service.request(response.config);
      } else {
        //console.log("superToken登录有误，无法获取token");
      }
      return;
    });
  }
}
function checkOriginParam(urlString) {
  // 创建 URL 对象
  const url = new URL(urlString);

  // 处理 hash 中的参数（如你的示例地址）
  const hashParams = url.hash.split('?')[1] || '';
  const params = new URLSearchParams(hashParams);

  // 如果 hash 中没有参数，则检查常规查询参数
  if (params.toString() === '') {
    return url.searchParams.has('origin');
  }

  return params.has('origin');
}
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    let res = response.data;
    if (res.code != null && res.code == 401) {
      if (
        localStorage.getItem('superToken') ==
          '407404EAEC845F1B91A104B80FE86D89' ||
        localStorage.getItem('superToken') == '5FD271D8A0AA315DD218801C0C3A0DEA'
      ) {
        getTokenLogin();
      } else {
        Message.closeAll();
        Message({
          message: '没有登录信息，重新登录',
          type: 'error',
          duration: 5 * 1000
        });
        console.log('401,1111111111111111');

        // 这里区分本地或者是线上环境
        if (
          window.location.href.indexOf('localhost') > -1 ||
          window.location.href.indexOf('192.168.60') > -1
        ) {
          router.push({ name: 'login' });
          return;
        }

        //从一览官网进入的情况下会有from=ylIndex参数
        if (window.location.href.indexOf('from=ylIndex') > -1) {
          store.dispatch('user/checkLogin');
          return;
        }

        let userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
          JSON.parse(localStorage.getItem('userInfo'));
          let admin_id = userInfo.admin_id;
          if (admin_id) {
            // 既有userInfo又有admin_id是老师 不做任何处理
            return;
          } else {
            //console.log("router", router);
            // 有userInfo没有admin_id是学生跳转回到登录页
            if (localStorage.getItem('origin')) {
              let query = {
                SecretKey: localStorage.getItem('SecretKey'),
                origin: 'loginPage'
              };
              router.push({ name: 'login', query });
            } else {
              // const url = 'https://www.com1001.com/admin/#/login';
              window.location.href = url;
            }
            console.log('1');
          }
        } else {
          // 没有userInfo是学生 跳转回到登录页

          console.log(
            '2',
            'window.location.href',
            checkOriginParam(window.location.href)
          );
          if (localStorage.getItem('origin')) {
            let query = {
              SecretKey: localStorage.getItem('SecretKey'),
              origin: 'loginPage'
            };
            router.push({ name: 'login', query });
          } else {
            // const url = 'https://www.com1001.com/admin/#/login';
            window.location.href = url;
          }
        }
        return;
      }
    }
    return res;
  },
  (error) => {
    //console.log("error报错" + error); // for debug
    if (
      error == 'Error: Request failed with status code 401' ||
      error == 'Error: Network Error'
    ) {
      console.log('401,22222222222222222222', window.location.href);
      //从一览官网进入的情况下会有from=ylIndex参数
      if (window.location.href.indexOf('from=ylIndex') > -1) {
        store.dispatch('user/checkLogin');
        return;
      }
      getTokenLogin();
      let userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        JSON.parse(localStorage.getItem('userInfo'));
        let admin_id = userInfo.admin_id;
        if (admin_id) {
          // 既有userInfo又有admin_id是老师 不做任何处理
          return;
        } else {
          //console.log("router", router);
          // 有userInfo没有admin_id是学生跳转回到登录页
          if (localStorage.getItem('origin')) {
            let query = {
              SecretKey: localStorage.getItem('SecretKey'),
              origin: 'loginPage'
            };
            router.push({ name: 'login', query });
          } else {
            // const url = 'https://www.com1001.com/admin/#/login';
            window.location.href = url;
          }
          console.log('3');
        }
      } else {
        // 没有userInfo是学生 跳转回到登录页
        if (localStorage.getItem('origin')) {
          let query = {
            SecretKey: localStorage.getItem('SecretKey'),
            origin: 'loginPage'
          };
          router.push({ name: 'login', query });
        } else {
          // const url = 'https://www.com1001.com/admin/#/login';
          window.location.href = url;
        }
        console.log('4');
      }
    } else {
      //先关闭所有message
      Message.closeAll();
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      });
    }
    return Promise.reject(error);
  }
);

export default service;
